/****
 * 新版购物车 @since 20130131-a
 */
(function($) {

	if (!$ || ! window.YM) return;

	var host = YM.login.servicePath,
	errorTip = '系统发生错误，请联系网站管理员！',
	errorParams = '无效的请求参数！';

	YM.namespace('YM.page.cart');

	YM.page.cart = {
		API: {
			//普通商品加入购物车
			ADD_GOODS_TO_CART_ACTION: host+ 'cart/addGoods.jspa',
			//goodsId and goodsNum
			//普通商品从购物车删除
			REMOVE_GOODS_FROM_CART_ACTION: host + 'cart/removeGoods.jspa',
			//cartKey and goodsId
			//修改普通商品在购物车的sku数量
			CHANGE_SKU_NUM_ACTION: host + 'cart/editGoodsNum.jspa',
			//赠品加入购物车
			ADD_PRESENT_TO_ACTION: host + 'cart/addPresent.jspa',
			//移除购物车中赠品
			REMOVE_PRESENT_FROM_CART_ACTION: host + 'cart/removePresent.jspa',
			//修改赠品数量
			CHANGE_PRESENT_SKU_NUM_ACTION: host + 'cart/editPresentNum.jspa',
			//添加优惠券
			ADD_COUPON_ACTION: host + 'cart/addVouchers.jspa',
			//移除优惠券
			REMOVE_COUPON_ACTION: host + 'cart/removeVouchers.jspa'
		},
		getVersion: function() {
			return '20130131-a';
		},
		static: {
			TO_BALANCE_URL: host + 'neworder/writeOrder2.jspa',
			SHOW_CART_URL: host + 'cart2/showCart.jspa'
		},
		init: function() {
			//TODO 页面初始化动作
		},
		/**
         * 约定opt,以下为opt下的参数
         *  goodsId(Integer) required #商品Id
         *  goodsNum(Intger) not #商品数量,默认为1
         *  callback(function) not required #回调 
         *  yearGoodsId(String) not required #年份Id
         *  houseId(Integer) not required #分仓Id
         *  adSource(String) not required #推广来源 
		*/
		addGoodsToCartV2: function(optp) {
		    optp = optp || {};
		    if (isNaN(optp.goodsId)) {
				YM.page.alert('您提交的商品ID有误!');
				return;
			}
			var callbackfn = optp.callback ||  function() {
				YM.page.header.cart.update();
			};
		    var opt = {};
			opt.goodsId=optp.goodsId;
			opt.goodsNum = optp.goodsNum || 1;
			if (!validateGoodsNum(opt.goodsNum)) {
				return;
			}
			if (optp.yearGoodsId) opt.yearGoodsId = optp.yearGoodsId;
			if (optp.houseId) opt.houseId = optp.houseId;
			if (optp.adSource) opt.adSource = optp.adSource;
			YM.dataproxy.ajax({
				url: YM.page.cart.API.ADD_GOODS_TO_CART_ACTION,
				type: 'POST',
				cache: false,
				data: opt,
				success: function(data) {
					ajaxCallback(data, callbackfn);
				},
				error: function() {
					YM.page.alert(errorTip);
				}
			});
		},
		/***
         * 约定yearGoodsId为字符串，以区别houseId, 第3到第6个参数可以缺省,顺序随意
         * @param goodsId(Integer) required #商品Id
         * @param goodsNum(Intger) required #商品数量
         * @param callback(function) not required #回调 
         * @param yearGoodsId(String) not required #年份Id
         * @param houseId(Integer) not required #分仓Id
         * @param adSource(String) not required #推广来源 
         */
		addGoodsToCart: function(goodsId, goodsNum, callback, yearGoodsId, houseId, adSource) {
			var yGoodsId, hId, advertisedSource, callbackfn = function() {
				YM.page.header.cart.update();
			};

			var argExcutor = function(arg) {
				typeof arg === 'string' ? (/^\d+$/.test(arg) ? yGoodsId = arg: advertisedSource = arg) : typeof arg === 'number' ? hId = arg: callbackfn = arg;
			};

			if (arguments.length < 2) {
				YM.page.alert(errorParams);
				return;
			}

			if (isNaN(goodsId) || isNaN(goodsNum)) {
				YM.page.alert('您提交的商品Id或商品数量不是有效的数字!');
				return;
			}

			if (!validateGoodsNum(goodsNum)) {
				return;
			}

			var splitedArgs = Array.prototype.slice.call(arguments, 2);
			for (var i = 0; i < splitedArgs.length; i++) {
				argExcutor(splitedArgs[i]);
			}

			YM.dataproxy.ajax({
				url: YM.page.cart.API.ADD_GOODS_TO_CART_ACTION,
				type: 'POST',
				cache: false,
				data: (function() {
					var postParams = {
						'goodsId': goodsId,
						'goodsNum': goodsNum
					};
					if (yGoodsId) postParams['yearGoodsId'] = yGoodsId;
					if (hId) postParams['houseId'] = hId;
					if (advertisedSource) postParams['adSource'] = advertisedSource;
					return postParams;
				})(),
				success: function(data) {
					ajaxCallback(data, callbackfn);
				},
				error: function() {
					YM.page.alert(errorTip);
				}
			});

		},
		addGoodsToCartBySingle: function(goodsId) {
			if (!goodsId) {
				YM.page.alert(errorParams);
				return;
			}
			var _this = this;
			var splitedGoodsIds = goodsId.split(',');
			for (var i = 0; i < splitedGoodsIds.length; i++) {
				_this.addGoodsToCart(splitedGoodsIds[i], 1);
			}
		},
		/***
         * 奥美
         */
		addGoodsToCartForAomei: function(callback) {
			var postParams = {
				'type': 'aomei'
			};
			commonSpecialaddCartFn(postParams, callback);
		},
		/***
         * 拍卖
         */
		addGoodsToCartForAuntion: function(bidIds, callback) {
			var postParams = {
				'type': 'auction',
				'bidIds': bidIds
			};
			commonSpecialaddCartFn(postParams, callback);
		},
		/***
         * 存酒库
         */
		addGoodsToCartForCellar: function(params, callback) {
//			var postParams = {
//				'type': 'fromCellar',
//				'cellarIds': cellarIds,
//				'quantities': quantities
//			};
			commonSpecialaddCartFn(params+"&type=fromCellar", callback);
		},
		/****
         * 也买学院
         */
		addGoodsToCartForCollege: function(classId, callback) {
			var postParams = {
				'type': 'college',
				'classId': classId
			};
			commonSpecialaddCartFn(postParams, callback);
		},
		/****
         * 积分兑换
         */
		addGoodsToCartForExchange: function(exchangeId, exchangeWayId, quantity, callback) {
			var postParams = {
				'type': 'exchange',
				'exchangeId': exchangeId,
				'exchangeWayId': exchangeWayId,
				'quantity': quantity
			};
			commonSpecialaddCartFn(postParams, callback);
		},
		/***
         * 礼品
         */
		addGoodsToCartForGift: function(giftDrawId, callback) {
			var callbackFn = callback || function() {
				YM.page.header.cart.update();
			};
			YM.dataproxy.ajax({
				url: YM.page.cart.API.ADD_GOODS_TO_CART_ACTION,
				type: 'POST',
				cache: false,
				data: {
					'type': 'gift',
					'giftDrawId': giftDrawId
				},
				success: function(data) {
					ajaxCallback(data, callbackFn);
				},
				error: function() {
					YM.page.alert(errorTip);
				}
			});
		},
		/****
         * 预售
         */
		addGoodsToCartForPresell: function(goodsId, goodsNum, callback) {
			var postParams = {
				'type': 'presell',
				'goodsId': goodsId,
				'goodsNum': goodsNum
			};
			commonSpecialaddCartFn(postParams, callback);
		},
		/***
         * 赠品
         */
		addPresentToCart: function(goodsId, goodsNum, cartType) {
			YM.dataproxy.ajax({
				url: YM.page.cart.API.ADD_PRESENT_TO_ACTION,
				type: 'POST',
				cache: false,
				data: {
					'goodsId': goodsId,
					'goodsNum': goodsNum,
					'cartType': cartType
				},
				success: function(data) {
					ajaxCallback(data, function() {
						window.location.reload();
					});
				},
				error: function() {
					YM.page.alert(errorTip);
				}
			});
		},
		/***
         * 移除赠品
         * @param presentKey
         * @param cartType
         */
		removePresentFromCart: function(presentKey, cartType, callback) {
			var callbackFn = function() {
				YM.page.header.cart.update();
			};
			if($.isFunction(callback)) callbackFn = callback;
			YM.dataproxy.ajax({
				url: YM.page.cart.API.REMOVE_PRESENT_FROM_CART_ACTION,
				type: 'POST',
				cache: false,
				data: {
					'presentKey': presentKey,
					'cartType': cartType
				},
				success: function(data) {
					ajaxCallback(data, function() {
//						window.location.reload();
					});
				},
				error: function() {
					YM.page.alert(errorTip);
				}
			});
		},
		/***
         * 修改赠品数量
         * @param presentKey
         * @param presentNum
         * @param cartType
         */
		changePresentSKUNum: function(presentKey, presentNum, cartType) {
			YM.dataproxy.ajax({
				url: YM.page.cart.API.CHANGE_PRESENT_SKU_NUM_ACTION,
				type: 'POST',
				cache: false,
				data: {
					'presentKey': presentKey,
					'presentNum': presentNum,
					'cartType': cartType
				},
				success: function(data) {
					ajaxCallback(data, function() {
//						window.location.reload();
					});
				},
				error: function() {
					YM.page.alert(errorTip);
				}
			});
		},
		/***
         * 修改购物车商品数量
         * @param goodsKey
         * @param goodsNum
         */
		changeSKUNum: function(goodsKey, goodsNum, cartType) {
			if (!validateGoodsNum(goodsNum)) {
				return;
			}

			YM.dataproxy.ajax({
				url: YM.page.cart.API.CHANGE_SKU_NUM_ACTION,
				type: 'POST',
				cache: false,
				data: {
					'goodsKey': goodsKey,
					'goodsNum': goodsNum,
					'cartType': cartType
				},
				success: function(data) {
					ajaxCallback(data, function() {
						window.location.reload();
					});
				},
				error: function() {
					YM.page.alert(errorTip);
				}
			});
		},
		/****
         * 商品从购物车中删除
         * @param goodsKey
         */
		removeGoodsFromCart: function(goodsKey, cartType, callback) {
			
			YM.dataproxy.ajax({
				url: YM.page.cart.API.REMOVE_GOODS_FROM_CART_ACTION,
				type: 'POST',
				cache: false,
				data: {
					'goodsKey': goodsKey,
					'cartType': cartType
				},
				success: function(data) {
					ajaxCallback(data, callback || function() {
						YM.page.header.cart.update();
					});
				},
				error: function() {
					YM.page.alert(errorTip);
				}
			});
		},
		/**
         * 添加到我的收藏
         * @param goodsId
         */
		addGoodsToFavorites: function(goodsId) {
			//loading goods.detail.js and call the method addFavorite 
		},
		/***
         * 使用优惠券
         */
		usingCoupon: function(cartType, couponCode, callback) {
			YM.dataproxy.ajax({
				url: YM.page.cart.API.ADD_COUPON_ACTION,
				type: 'POST',
				cache: false,
				data: {
					'cartType': cartType,
					'couponCode': couponCode
				},
				success: function(data) {
					ajaxCallback(data, callback || function() {
						YM.page.alert("兑换成功！", function(){
//							window.location.reload();
						});
					});
				},
				error: function() {
					YM.page.alert(errorTip);
				}
			});
		},
		/***
         * 移除优惠券
         */
		removeCoupon: function(cartType, vouchersKey){
			YM.dataproxy.ajax({
				url: YM.page.cart.API.REMOVE_COUPON_ACTION,
				type: 'POST',
				cache: false,
				data: {
					'cartType': cartType,
					'vouchersKey': vouchersKey
				},
				success: function(data) {
					ajaxCallback(data, function() {
//						window.location.reload();
					});
				},
				error: function() {
					YM.page.alert(errorTip);
				}
			});
		}
	};

	function ajaxCallback(data, func) {
		if (!data.error) {
			if(data.messageList!='' && data.messageList.length > 0){ // 警告信息或提示信息
				var message = '';
				for (var i = 0; i < data.messageList.length; i++) {
					message += data.messageList[i] + '<br />';
				}
				YM.page.alert(message, function(){
					window.location.reload();
				});
			}else{
				func.call(this);
			}
		} else {
			var message = '';
			for (var i = 0; i < data.messageList.length; i++) {
				message += data.messageList[i] + '<br />';
			}
			YM.page.alert(message);
		}
	}

	function validateGoodsNum(goodsNum) {
		if (!/^[1-9]\d*$/.test(goodsNum)) {
			YM.page.alert('商品数量必须为正整数!');
			return false;
		}
		return true;
	}

	function commonSpecialaddCartFn(postParams, callback) {
		var callbackFn = callback || function() {
			YM.page.header.cart.update();
		};
		YM.dataproxy.ajax({
			url: YM.page.cart.API.ADD_GOODS_TO_CART_ACTION,
			type: 'POST',
			cache: false,
			data: postParams,
			success: function(data) {
				ajaxCallback(data, callbackFn);
			},
			error: function() {
				YM.page.alert(errorTip);
			}
		});
	}
	
	//临时覆盖线上老的加入购物车方法，已兼容线上js版本
	YM.namespace('YM.page.header.cart');
	YM.page.header.cart.addGood = function(goodsId, amountId, goodsYearId) {
		var goodsNum = 1;
		if (amountId) {
			goodsNum = (isNaN(amountId)) ? $('#'+amountId).val().trim() : amountId;
		}
		YM.page.cart.addGoodsToCartV2({goodsId:goodsId, goodsNum:goodsNum, yearGoodsId:goodsYearId});
	}; 
	YM.page.header.cart.delGood = function(goodsId, cartType) {
		YM.page.cart.removeGoodsFromCart(goodsId, cartType, function() {
			YM.page.header.cart.update();
		});
	};


	//整个页面的数据输入控制
	//	 function bindGlobalNumInput(){
	//		 $('.class').bind()
	//	 }
	$(document).ready(function() {
		YM.page.cart.init();
	});
})(jQuery);

